package cn.ilikes.tools.hbase.jpa.metadatas.processor.processores;

import javax.persistence.Table;

import org.slf4j.Logger;

import cn.ilikes.tools.hbase.jpa.annotations.Index;
import cn.ilikes.tools.hbase.jpa.metadatas.EntityMetaDataImpl;
import cn.ilikes.tools.hbase.jpa.metadatas.IEntityMetaData;
import cn.ilikes.tools.hbase.jpa.metadatas.elements.EntityIndexImpl;
import cn.ilikes.tools.hbase.jpa.metadatas.processor.validators.EntityIndexValidator;
import cn.ilikes.tools.hbase.jpa.metadatas.processor.validators.EntityTableAndEntityValidator;
import cn.ilikes.tools.hbase.jpa.metadatas.processor.validators.EntityValidatorException;
import cn.ilikes.tools.logs.Loggerfactory;

/**
 * @table @entity
 * @author fack
 * 
 */
public class EntityTableProcessors implements Processors {

	private Logger logger = Loggerfactory.instance(EntityTableProcessors.class);

	private EntityTableAndEntityValidator entityTableAndEntityValidator = new EntityTableAndEntityValidator();

	private EntityIndexValidator entityIndexValidator = new EntityIndexValidator();

	@Override
	public void validators(Class<?> clazz, IEntityMetaData metadata) throws EntityValidatorException {
		if (Loggerfactory.isdebug(logger))
			logger.debug("start  validators  entity   table   ");
		try {
			entityTableAndEntityValidator.entityValidator(clazz, metadata);
			entityIndexValidator.entityValidator(clazz, metadata);
		} catch (EntityValidatorException e) {
			throw new EntityValidatorException(e);
		}
	}

	@Override
	public void processors(Class<?> clazz, IEntityMetaData metadata) throws ElementProcessorException {
		if (Loggerfactory.isdebug(logger))
			logger.debug("start  processors entity   table  ");
		validators(clazz, metadata);
		EntityMetaDataImpl entityMetaDataImpl = (EntityMetaDataImpl) metadata;
		Table table = clazz.getAnnotation(Table.class);
		String entityTableName = table.name();
		entityMetaDataImpl.setEntityTableName(entityTableName);
		entityMetaDataImpl.setEntityName(clazz.getSimpleName());
		String schema = table.schema();
		entityMetaDataImpl.setSchema(schema);
		entityMetaDataImpl.setEntityClazz(clazz);
		entityMetaDataImpl.setInterfaces(clazz.getInterfaces());

		Index index = clazz.getAnnotation(Index.class);
		//前面已经验证
		if (index != null) {
			EntityIndexImpl entityIndexImpl = new EntityIndexImpl();
			String indexName = index.name();
			if (indexName == null || indexName.isEmpty())
				indexName = entityMetaDataImpl.getEntityClazz().getSimpleName();
			entityIndexImpl.setIndexName(indexName);
			entityIndexImpl.setIndexable(index.index().equals(Index.index.yes) ? true : false);
			entityMetaDataImpl.setEntityIndex(entityIndexImpl);
		}

	}

}
